<template>
  <div v-loading="loading" element-loading-text="加载中..." class="new_out_storage">
    <div class="main">
      <header class="header">
        <div class="title">
          <div v-if="route.params.id" class="out_storage">
            <i class="iconfont icon-detail"></i>
            <div class="text">入库单号：{{ detail.outboundNo }}</div>
          </div>
          <div v-else class="new">新增调拨入库</div>
          <div v-if="route.params.id" class="title">
            <!-- <div class="text">出库编号:{{ detail.outboundNo }}</div> -->
            <template v-if="Number(status) === 1">
              <h-status v-if="detail.submitType === 0" type="warning">待审核</h-status>
              <h-status v-else>未提交</h-status>
            </template>
            <h-status v-if="Number(status) === 3" type="info">已驳回</h-status>
          </div>
        </div>

        <div class="btn_group">
          <HPlainButton
            v-if="Number(status) !== 1 || detail.submitType !== 0"
            v-permission="'outb_audit'"
            type="warning"
            @click="onSave(0)"
            >保存并提交</HPlainButton
          >
          <HPlainButton v-if="Number(status) !== 1" @click="onSave(1)">保存</HPlainButton>
          <HButton @click="onCancel">取消</HButton>
        </div>
      </header>

      <div class="divider_line"></div>

      <div class="body">
        <div ref="formContainerRef" class="form_container">
          <el-form ref="formInstance" inline-message :model="form" :rules="rules" label-width="85">
            <div class="form_item">
              <!-- 单据日期 -->
              <!-- <el-form-item label="单据日期">
                <el-date-picker
                  v-model="form.createTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm"
                  :default-value="new Date()"
                />
              </el-form-item> -->

              <!-- 单据类型 -->
              <el-form-item label="单据类型" prop="typeId">
                <!-- <el-select
                  v-model="form.typeId"
                  :loading="getWarehouseInTypeOptionsLoading"
                  placeholder="单据类型"
                  filterable
                  clearable
                  :filter-method="handleGetWarehouseOutOptions"
                  disabled
                >
                  <el-option
                    v-for="(item, index) in warehouseInTypeOptions"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select> -->
                <el-input disabled :model-value="'调拨入库'" />
              </el-form-item>

              <!-- 调入部门 -->
              <el-form-item label="调入部门">
                <el-input placeholder="调入部门" disabled :model-value="networkName" />
              </el-form-item>

              <!-- 单据备注 -->
              <el-form-item label="单据备注">
                <el-input
                  v-model.trim="form.remark"
                  clearable
                  placeholder="单据备注"
                  type="textarea"
                  resize="both"
                  maxlength="200"
                  show-word-limit
                  :disabled="isDisabeldUpdate"
                />
              </el-form-item>
            </div>

            <div class="form_item">
              <!-- 调出仓 -->
              <el-form-item label="调出仓">
                <el-select
                  v-model="allotOutWarehouseIdForMultipleFillIn"
                  placeholder="请选择"
                  filterable
                  clearable
                  :filter-method="handleGetAllotOutWarehouseOptions"
                  :loading="getAllotOutWarehouseOptionsLoading"
                  :disabled="isDisabeldUpdate"
                  @change="onMultipleFillInAllotOutId"
                >
                  <el-option
                    v-for="(item, index) in allotOutWarehouseOptions"
                    :key="index"
                    :disabled="item.disabled"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 调入仓 -->
              <el-form-item label="调入仓">
                <el-select
                  v-model="allotInWarehouseIdForMultipleFillIn"
                  placeholder="请选择"
                  filterable
                  clearable
                  :filter-method="handleGetAllotInWarehouseOptions"
                  :loading="getAllotOutWarehouseOptionsLoading"
                  :disabled="userStore.$state.role[0].roleType === 2 || isDisabeldUpdate"
                  @change="onMultipleFillInAllotInId"
                >
                  <el-option
                    v-for="(item, index) in allotOutWarehouseOptions"
                    :key="index"
                    :disabled="item.disabled"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 联系人 -->
              <el-form-item label="联系人" prop="username">
                <el-input
                  v-model.trim="form.username"
                  clearable
                  placeholder="联系人"
                  :disabled="isDisabeldUpdate"
                />
              </el-form-item>
            </div>

            <div class="form_item">
              <!-- 手机号码 -->
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model.trim="form.phone"
                  placeholder="请输入手机号码"
                  maxlength="11"
                  :disabled="isDisabeldUpdate"
                />
              </el-form-item>

              <!-- 收货地址 -->
              <el-form-item label="收货地址" prop="province">
                <single-address
                  ref="singleAddressInstance"
                  :address="receiptCustomerAddress"
                  :disabled="isDisabeldUpdate"
                  @change="handleReceiptAddressChange"
                />
              </el-form-item>

              <!-- 详细地址 -->
              <el-form-item label="详细地址" prop="address">
                <el-input
                  v-model.trim="form.address"
                  clearable
                  placeholder="详细地址"
                  maxlength="200"
                  show-word-limit
                  resize="both"
                  type="textarea"
                  :disabled="isDisabeldUpdate"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="table-container">
          <div class="title">设备列表</div>
          <div class="table">
            <el-table
              ref="goodTableInstance"
              :border="true"
              :data="goodList"
              height="100%"
              show-summary
              :summary-method="getSummary"
              resizable
              stripe
              :row-class-name="getRowClassName"
            >
              <!-- 序号 -->
              <el-table-column
                label="序号"
                width="60"
                fixed="left"
                :align="'center'"
                type="index"
              />

              <!-- 调出仓 -->
              <el-table-column prop="transferOutWarehouse" label="调出仓" width="150">
                <template #default="{ row, $index }">
                  <el-select
                    v-model="row.storeId"
                    placeholder="请选择调出仓"
                    filterable
                    clearable
                    disabled
                    :filter-method="handleGetAllotOutWarehouseOptions"
                    :loading="getAllotOutWarehouseOptionsLoading"
                  >
                    <el-option
                      v-for="(item, index) in allotOutWarehouseOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                      :disabled="item.disabled"
                      @click="handleAllotOutWarehouseClick(item, $index)"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <!-- 可用库存 -->
              <el-table-column show-overflow-tooltip label="可用库存" width="95">
                <template #header>
                  <span>可用库存</span>
                  <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </template>
                <template #default="{ row }">
                  <span>{{ row.storeStock }}</span>
                </template>
              </el-table-column>

              <!-- 调入仓 -->
              <el-table-column prop="transferInWarehouse" label="调入仓" width="150">
                <template #header>
                  <span style="color: #a8abb2">调入仓</span>
                </template>
                <template #default="{ row, $index }">
                  <el-select
                    v-model="row.inStoreId"
                    :loading="getAllotInWarehouseOptionsLoading"
                    placeholder="请选择调入仓"
                    filterable
                    disabled
                    :filter-method="handleGetAllotInWarehouseOptions"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in allotInWarehouseOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                      :disabled="item.disabled"
                      @click="handleAllotInWarehouseClick(item, $index)"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <!-- 可用库存 -->
              <el-table-column show-overflow-tooltip label="可用库存" width="95">
                <template #header>
                  <span style="color: #a8abb2">可用库存</span>
                  <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </template>
                <template #default="{ row }">
                  <span>{{ row.inStoreStock }}</span>
                </template>
              </el-table-column>

              <!-- 设备编号 -->
              <el-table-column
                prop="goodsCode"
                show-overflow-tooltip
                label="设备编号"
                width="160"
              />

              <!-- 类型 -->
              <!-- <el-table-column show-overflow-tooltip label="类型" width="50">
                <template #default="{ row }">
                  <span>{{ row.type === 1 ? '成品' : '物料' }}</span>
                </template>
              </el-table-column> -->

              <!-- 设备名称 -->
              <el-table-column
                prop="goodsName"
                show-overflow-tooltip
                label="设备名称"
                width="140"
              />

              <!-- 申请数量 -->
              <el-table-column prop="applyQty" show-overflow-tooltip label="申请数量" width="140">
                <template #header>
                  申请数量
                  <el-popover
                    placement="top"
                    trigger="click"
                    :width="160"
                    :visible="multipleChangeQtyPopoverVisible"
                  >
                    <h5 style="margin-bottom: 10px">批量填充出库数量</h5>
                    <el-input
                      v-model.trim="allQty"
                      placeholder="请输入出库数量"
                      maxlength="5"
                      @input="handleChangeAllQty"
                      @keyup.enter="onMultipleChangeQty"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="onMultipleChangeQty"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <span
                        v-if="!isDisabeldUpdate"
                        style="
                          font-size: 11px;
                          background-color: #fff;
                          cursor: pointer;
                          color: #007cff;
                        "
                        @click="multipleChangeQtyPopoverVisible = !multipleChangeQtyPopoverVisible"
                        >批量</span
                      >
                    </template>
                  </el-popover>
                </template>
                <template #default="{ row, $index }">
                  <el-input
                    v-if="!row.isFixed"
                    v-model.trim="row.applyQty"
                    maxlength="5"
                    placeholder="请输入出库数量"
                    :disabled="isDisabeldUpdate"
                    @input="(applyQty: string) => handleApplyQtyInput(applyQty, $index)"
                  />
                </template>
              </el-table-column>

              <!-- 规格 -->
              <el-table-column prop="goodsSpec" show-overflow-tooltip label="规格" width="160" />

              <!-- 分类 -->
              <el-table-column prop="classify" show-overflow-tooltip label="分类" min-width="120" />

              <!-- 单位 -->
              <el-table-column prop="unit" show-overflow-tooltip label="单位" width="60" />

              <!-- 选择序列号 -->
              <!-- <el-table-column
                prop="stockCodeVos"
                show-overflow-tooltip
                label="选择序列号"
                width="160"
              >
                <template #default="{ row }">
                  <template v-if="!row.isFixed">
                    <h-link v-if="row.snCodes.length > 0" @click="handleFillSnCodeClick(row)">{{
                      row.snCodes.join('、')
                    }}</h-link>
                    <h-link v-else @click="handleFillSnCodeClick(row)">选择序列号</h-link>
                  </template>
                </template>
              </el-table-column> -->

              <!-- 备注 -->
              <el-table-column prop="remark" show-overflow-tooltip label="备注" width="200">
                <template #default="{ row }">
                  <el-input
                    v-if="!row.isFixed"
                    v-model.trim="row.remark"
                    type="text"
                    clearable
                    placeholder="请输入备注"
                    maxlength="100"
                    :disabled="isDisabeldUpdate"
                  />
                </template>
              </el-table-column>

              <!-- 紧急程度 -->
              <el-table-column show-overflow-tooltip label="紧急程度" width="140">
                <template #default="{ row }">
                  <el-select
                    v-if="!row.isFixed"
                    v-model="row.grade"
                    placeholder="请选择紧急程度"
                    :disabled="isDisabeldUpdate"
                  >
                    <el-option :value="1" label="一般" />
                    <el-option :value="2" label="紧急" />
                    <el-option :value="3" label="特别紧急" />
                  </el-select>
                </template>
              </el-table-column>

              <!-- 操作 -->
              <el-table-column v-if="!isDisabeldUpdate" width="90" fixed="right" label="操作">
                <template #header>
                  <h-link @click="goodSelectModalVisible = true">添加物料</h-link>
                </template>
                <template #default="{ $index }">
                  <h-link type="error" @click="handleDelGood($index)">删除</h-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <good-select-modal
      v-model:visible="goodSelectModalVisible"
      :default-select-good-list="defaultSelectGoodList"
      :product-type="2"
      @confirm="handleGoodSelectModalConfirm"
      @good-remove="handleGoodSelectModalRemove"
    />

    <sn-code-fill-modal v-model="snCodeFillModalVisible" :good="fillingSnCodeGood" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import {
    FormInstance,
    ElTooltip,
    ElIcon,
    ElPopover,
    TableColumnCtx,
    TableInstance,
  } from 'element-plus'
  import _ from 'lodash'
  import { QuestionFilled } from '@element-plus/icons-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Good } from './types'
  import routeComponentName from '@/config/route-component-name'
  import {
    useGetWarehouseOutReceiptCustomerList,
    useGetWarehouseAndPersonAddressList,
    useGetGoodStock,
  } from '@/services/pages/storage/useWarehouseOut'
  import { phone } from '@/utils/validate'
  import GoodSelectModal from '@/components/pages/Warehouse/out/GoodSelectModal.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import fixedData from '@/config/fixed-data/warehouse/out-store'
  import {
    useAllotWarehouseInOrOutFormSave,
    useGetAllotInWarehouseDetail,
    useGetAllotInWarehouseMaterialList,
    useUpdateAllotInWarehouse,
    useGetAccountNetworkInfoAndInWarehouse,
  } from '@/services/pages/storage/useWarehouse'
  import snCodeFillModal from '@/components/pages/Warehouse/allot/sn-code-fill-modal.vue'
  import { useUserStore } from '@/store/modules/user'
  import { useGetNetworkInfoByWarehouseId } from '@/services/pages/network/useNetwork'

  const {
    currentAccountsNetworkInWarehouseInfo,
    getCurrentAccountsNetworkInWarehouseInfoLoading,
    getCurrentAccountsNetworkInWarehouseInfo,
  } = useGetAccountNetworkInfoAndInWarehouse()
  const { getCustomer: getReceiptCustomerList } = useGetWarehouseOutReceiptCustomerList()
  const {
    list: allotOutWarehouseOptions,
    getListParam: getAllotOutWarehouseOptionsParam,
    getListLoading: getAllotOutWarehouseOptionsLoading,
    getList: getAllotOutWarehouseOptions,
  } = useGetWarehouseAndPersonAddressList()
  const {
    list: allotInWarehouseOptions,
    getListParam: getAllotInWarehouseOptionsParam,
    getListLoading: getAllotInWarehouseOptionsLoading,
    getList: getAllotInWarehouseOptions,
  } = useGetWarehouseAndPersonAddressList()
  const { goodStock, getGoodStockParam, getGoodStockLoading, getWarehouseGoodStock } =
    useGetGoodStock()
  const { form, formSaveLoading, submit, resetForm } = useAllotWarehouseInOrOutFormSave()
  const { detail, getDetailLoading, getDetail } = useGetAllotInWarehouseDetail()
  const {
    materialList,
    getListLoading: getMaterialListLoading,
    getList: getMaterialList,
  } = useGetAllotInWarehouseMaterialList()
  const { updateForm, updateLoading, update } = useUpdateAllotInWarehouse()
  const { networkInfo, getNetworkInfoLoading, getNetworkInfo } = useGetNetworkInfoByWarehouseId()

  defineOptions({
    name: routeComponentName.storage.warehouseAllotInCreate,
  })

  /**
   * 是否禁止修改
   */
  const isDisabeldUpdate = computed(() => {
    return route.params.id && detail.value.submitType === 0
  })

  // 调入部门
  const networkName = ref('')

  // 客户状态管理
  const userStore = useUserStore()

  // 调出仓id，用于批量填充
  const allotOutWarehouseIdForMultipleFillIn = ref('')

  // 调入仓id，用于批量填充
  const allotInWarehouseIdForMultipleFillIn = ref('')

  // 全局路由对象
  const router = useRouter()

  // 激活路由对象
  const route = useRoute()

  // 标签状态管理
  const tagsViewStore = useTagsViewStore()

  // 设备表格组件实例
  const goodTableInstance = ref<TableInstance | null>(null)

  /**
   * 是否校验仓库、仓位、序列号是否有填写
   */
  const isVerifyWarehouse = ref(false)

  // 正在填充序列号的设备
  const fillingSnCodeGood = ref<Good>({
    applyQty: '',
    goodsCode: '',
    goodsId: '',
    goodsName: '',
    goodsSpec: '',
    goodsSpecId: '',
    grade: 1,
    id: '',
    inStore: '',
    inStoreId: '',
    inStorePosition: '',
    inStorePositionId: '',
    qty: '',
    remark: '',
    snCodes: [],
    store: '',
    storeId: '',
    storePosition: '',
    storePositionId: '',
    type: 1,
    unit: '',
    classify: '',
    storeStock: 0,
    inStoreStock: 0,
  })

  // 序列号选择弹窗显示状态
  const snCodeFillModalVisible = ref(false)

  // 批量更新数量弹出框显示状态
  const multipleChangeQtyPopoverVisible = ref(false)

  // 所有数量
  const allQty = ref('')

  // 设备选择弹窗显示状态
  const goodSelectModalVisible = ref(false)

  // 设备列表
  const goodList = ref<Array<Good>>([])

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 表单校验规则
  const rules = {
    typeId: [{ required: true, message: '出库类型', trigger: ['blur', 'change'] }],
    receiptVo: {
      receiptAddrType: [{ required: true, message: '出库类型', trigger: ['blur', 'change'] }],
      receiptName: [{ required: true, message: '收货人姓名', trigger: ['blur', 'change'] }],
      phone: [
        { required: true, message: '请输入手机号码', trigger: ['blur', 'change'] },
        { validator: phone(form.value.phone), trigger: ['blur', 'change'] },
      ],
      receiptAddress: [{ required: true, message: '请输入详细地址', trigger: ['blur', 'change'] }],
      province: [
        {
          required: true,
          validator: (rule, value, callback) => {
            const { province, city, area } = form.value
            if (!province || !city || !area) {
              callback(new Error('请选择地址'))
              return
            }
            callback()
          },
          trigger: ['blur', 'change'],
        },
      ],
    },
    storePositionId: [{ required: true, message: '仓库仓位', trigger: ['blur', 'change'] }],
    storeType: [{ required: true, message: '仓库类型', trigger: ['blur', 'change'] }],
  }

  // 收货公司地址
  const receiptCustomerAddress = computed(() => {
    return {
      province: form.value.province,
      city: form.value.city,
      area: form.value.area,
      town: '',
    }
  })

  // 收货地址选择组件实例
  const singleAddressInstance = ref<InstanceType<typeof SingleAddress> | null>(null)

  // 用于设备选择弹窗回显
  const defaultSelectGoodList = computed(() => {
    return goodList.value.map((good) => {
      return {
        goodId: good.goodsId,
        goodSpecId: good.goodsSpecId,
      }
    })
  })

  // 加载
  const loading = computed(() => {
    return (
      formSaveLoading.value ||
      getDetailLoading.value ||
      getMaterialListLoading.value ||
      updateLoading.value ||
      getCurrentAccountsNetworkInWarehouseInfoLoading.value ||
      getNetworkInfoLoading.value ||
      getGoodStockLoading.value
    )
  })

  /**
   * 单据状态
   */
  const status = computed(() => {
    return route.params.type
  })

  /**
   * 表格的调出仓的仓库选项点击事件
   * @param {WarehouseOutWarehouseAndPersonAddress} warehouseOption - 点击的仓库
   * @param {number} index - 物料索引
   */
  const handleAllotOutWarehouseClick = async (
    warehouseOption: WarehouseOutWarehouseAndPersonAddress,
    index: number,
  ) => {
    const good = goodList.value[index]
    if (good) {
      goodList.value[index].store = warehouseOption.name
      goodList.value[index].storeId = warehouseOption.id
    }
  }

  /**
   * 表格的调入仓的仓库选项点击事件
   * @param {WarehouseOutWarehouseAndPersonAddress} warehouseOption - 点击的仓库
   * @param {number} index - 物料索引
   */
  const handleAllotInWarehouseClick = async (
    warehouseOption: WarehouseOutWarehouseAndPersonAddress,
    index: number,
  ) => {
    const good = goodList.value[index]
    if (good) {
      goodList.value[index].inStore = warehouseOption.name
      goodList.value[index].inStoreId = warehouseOption.id
      getGoodStockParam.value = {
        goodsId: good.goodsId,
        goodsSpecId: good.goodsSpecId,
        storeId: good.storeId,
        storePositionId: '',
        type: good.type,
      }
      await getWarehouseGoodStock()
      goodList.value[index].inStoreStock = goodStock.value.systemStock
    }
  }

  /**
   * 更新所有物料的库存
   */
  const updateAllGoodStock = async () => {
    for (let i = 0; i < goodList.value.length; i++) {
      const item = goodList.value[i]
      if (!item || !item.goodsId || !item.goodsSpecId) {
        return
      }
      if (item.storeId) {
        getGoodStockParam.value = {
          goodsId: goodList.value[i].goodsId,
          goodsSpecId: goodList.value[i].goodsSpecId,
          storeId: goodList.value[i].storeId,
          storePositionId: '',
          type: goodList.value[i].type,
        }
        await getWarehouseGoodStock()
        goodList.value[i].storeStock = goodStock.value.systemStock
      }

      if (item.inStoreId) {
        getGoodStockParam.value = {
          goodsId: goodList.value[i].goodsId,
          goodsSpecId: goodList.value[i].goodsSpecId,
          storeId: goodList.value[i].inStoreId,
          storePositionId: '',
          type: goodList.value[i].type,
        }
        await getWarehouseGoodStock()
        goodList.value[i].inStoreStock = goodStock.value.systemStock
      }
    }
  }

  /**
   * 表单的调出仓选择事件
   */
  const onMultipleFillInAllotOutId = async () => {
    const warehouseOption = allotOutWarehouseOptions.value.find(
      (item) => item.id === allotOutWarehouseIdForMultipleFillIn.value,
    )
    if (warehouseOption.id && warehouseOption.name) {
      for (let i = 0; i < goodList.value.length; i++) {
        goodList.value[i].store = warehouseOption.name
        goodList.value[i].storeId = warehouseOption.id
      }
    }

    updateAllGoodStock()
  }

  /**
   * 表单的调入仓选择事件
   */
  const onMultipleFillInAllotInId = async () => {
    const warehouseOption = allotInWarehouseOptions.value.find(
      (item) => item.id === allotInWarehouseIdForMultipleFillIn.value,
    )
    if (warehouseOption.id && warehouseOption.name) {
      goodList.value = goodList.value.map((item) => {
        item.inStore = warehouseOption.name
        item.inStoreId = warehouseOption.id
        return item
      })
    }

    await getNetworkInfo(allotInWarehouseIdForMultipleFillIn.value)
    networkName.value = networkInfo.value.networkName
    updateAllGoodStock()
  }

  /**
   * 调出仓列表搜索事件
   * @param {string} keyword - 搜索关键字
   */
  const handleGetAllotOutWarehouseOptions = _.debounce((keyword: string) => {
    if (getAllotOutWarehouseOptionsParam.value.name !== keyword) {
      getAllotOutWarehouseOptionsParam.value.name = keyword
      getAllotOutWarehouseOptions(0)
    }
  }, 600)

  /**
   * 调入仓列表搜索事件
   * @param {string} keyword - 搜索关键字
   */
  const handleGetAllotInWarehouseOptions = _.debounce((keyword: string) => {
    if (getAllotInWarehouseOptionsParam.value.name !== keyword) {
      getAllotInWarehouseOptionsParam.value.name = keyword
      getAllotInWarehouseOptions(0)
    }
  }, 600)

  /**
   * 收货地址更新事件
   * @param {Object} address - 地址
   * @param {String} address.province - 省
   * @param {String} address.city - 市
   * @param {String} address.area - 区
   * @param {String} address.town - 镇
   */
  const handleReceiptAddressChange = (address: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    form.value.province = address.province
    form.value.city = address.city
    form.value.area = address.area
  }

  /**
   * 设备列表滚动到指定位置
   * @param top - 指定沿 Y 轴滚动元素的像素数
   */
  const tableScrollToSpecifyPosition = (top = 0) => {
    if (goodTableInstance.value) {
      goodTableInstance.value.scrollTo({
        top,
        left: 0,
        behavior: 'smooth',
      })
    }
  }

  /**
   * 表单和表格校验
   */
  const formAndTableValidate = async () => {
    if (!formInstance.value) {
      return Promise.reject('')
    }

    try {
      await formInstance.value.validate()
      if (goodList.value.length <= 0) {
        HMessageBox.error('请选择设备')
        return Promise.reject('请选择设备')
      }
      isVerifyWarehouse.value = true
      for (let i = 0; i < goodList.value.length; i++) {
        const good = goodList.value[i]
        if (!good.storeId) {
          tableScrollToSpecifyPosition(i * 40)
          HMessageBox.error('请选择调出仓')
          return Promise.reject('请选择调出仓')
        }

        if (!good.inStoreId) {
          tableScrollToSpecifyPosition(i * 40)
          HMessageBox.error('请选择调入仓')
          return Promise.reject('请选择调入仓')
        }
      }
    } catch (error) {
      return Promise.reject('')
    }
  }

  /**
   * 保存事件
   * @param {0|1} submitType - 提交类型：0-提交，1-仅保存
   */
  const onSave = async (submitType: 0 | 1) => {
    try {
      await formAndTableValidate()
      form.value.typeName = '调拨入库'
      form.value.storeMaterialVos = goodList.value.map((item) => {
        return {
          applyQty: Number(item.applyQty) ? item.applyQty : '1',
          goodsCode: item.goodsCode,
          goodsId: item.goodsId,
          goodsName: item.goodsName,
          goodsSpec: item.goodsSpec,
          goodsSpecId: item.goodsSpecId,
          grade: item.grade,
          id: item.id || '',
          inStore: item.inStore,
          inStoreId: item.inStoreId,
          inStorePosition: '',
          inStorePositionId: '',
          qty: '',
          remark: item.remark,
          snCodes: [],
          store: item.store,
          storeId: item.storeId,
          storePosition: '',
          storePositionId: '',
          type: item.type,
        }
      })
      let res: APIResponse = {
        code: 0,
        success: false,
        message: '',
        data: {
          row: {},
        },
        hasOtherCode: false,
        otherCodePrefix: '',
      }
      if (route.params.id) {
        updateForm.value = form.value
        res = await update(route.params.id as string, submitType)
      } else {
        res = await submit(2, submitType)
      }
      if (res.code === 20000) {
        HMessage.success(route.params.id ? '修改调拨入库成功' : '创建调拨入库成功')
        tagsViewStore.delView(route.path)
        router.push({ path: '/storage/allot/in', query: { isUpdate: 1 } })
        resetForm()
        return
      }
      HMessageBox.error(res.message)
    } catch (error) {
      // error
    }
  }

  /**
   * 获取表格行的类名，主要用于第一行数据固定显示
   * @param {Object} data - 表格行数据
   */
  const getRowClassName = (data: { row: Good; rowIndex: number }) => {
    if (data.rowIndex === 0) {
      return 'fixed-row'
    }
  }

  /**
   * 设备选择弹窗确认事件
   * @param {Array<WarehouseOutGood>} goodSelectionList - 设备选择列表
   */
  const handleGoodSelectModalConfirm = (goodSelectionList: Array<WarehouseOutGood>) => {
    goodSelectionList.forEach((good) => {
      const index = goodList.value.findIndex(
        (item) => item.goodsId === good.id && item.goodsSpecId === good.specId,
      )
      const inWarehouse = allotInWarehouseOptions.value.find(
        (item) => item.id === allotInWarehouseIdForMultipleFillIn.value,
      )
      const outWarehouse = allotOutWarehouseOptions.value.find(
        (item) => item.id === allotOutWarehouseIdForMultipleFillIn.value,
      )
      if (index === -1) {
        goodList.value.push({
          applyQty: '1',
          goodsCode: good.code,
          goodsId: good.id,
          goodsName: good.name,
          goodsSpec: good.specName,
          goodsSpecId: good.specId,
          grade: 1,
          id: '',
          inStore: inWarehouse ? inWarehouse.name : '',
          inStoreId: inWarehouse ? inWarehouse.id : '',
          inStorePosition: '',
          inStorePositionId: '',
          qty: '1',
          remark: '',
          snCodes: [],
          store: outWarehouse ? outWarehouse.name : '',
          storeId: outWarehouse ? outWarehouse.id : '',
          storePosition: '',
          storePositionId: '',
          type: good.goodsType,
          classify: good.type,
          unit: good.unit,
          storeStock: 0,
          inStoreStock: 0,
        })
      }
    })

    updateAllGoodStock()
  }

  /**
   * 设备列表初始化
   */
  const goodListInit = () => {
    goodList.value = []
  }

  /**
   * 设备选择弹窗删除事件
   * @param {Array<WarehouseOutGood>} goodRemoveList - 设备删除列表
   */
  const handleGoodSelectModalRemove = (goodRemoveList: Array<WarehouseOutGood>) => {
    goodRemoveList.forEach((item) => {
      const index = goodList.value.findIndex(
        (good) => good.goodsId === item.id && good.goodsSpecId === item.specId,
      )
      if (index >= 0) {
        goodList.value.splice(index, 1)
      }
    })
  }

  /**
   * 批量更新数量
   */
  const onMultipleChangeQty = () => {
    goodList.value = goodList.value.map((item) => {
      return { ...item, applyQty: Number(allQty.value) ? allQty.value : '1' }
    })
    multipleChangeQtyPopoverVisible.value = false
  }

  /**
   * 申请数量更新事件
   * @param applyQty - 申请数量
   * @param index - 设备索引
   */
  const handleApplyQtyInput = (applyQty: string, index: number) => {
    applyQty = applyQty.replace(/[^\d]/g, '')
    if (Number(applyQty) > 99999) {
      applyQty = '99999'
    }

    // if (Number(applyQty) <= 0) {
    //   applyQty = '1'
    // }

    goodList.value[index].applyQty = applyQty
  }

  /**
   * 数量批量更新事件
   */
  const handleChangeAllQty = () => {
    allQty.value = allQty.value.replace(/[^\d]/g, '')
    if (Number(allQty.value) > 99999) {
      allQty.value = '99999'
    }

    // if (Number(allQty.value) <= 0) {
    //   allQty.value = '1'
    // }

    goodList.value = goodList.value.map((good) => {
      return {
        ...good,
        qty: allQty.value,
      }
    })
  }

  /**
   * 表格合计
   */
  const getSummary = (param: { columns: TableColumnCtx<Good>[]; data: Array<Good> }) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[0] = '合计'
        return
      }

      if (column.property === 'applyQty') {
        let total = 0
        data.forEach((good) => {
          total += Number(good.applyQty)
        })
        sums[index] = String(total)
      }
    })

    return sums
  }

  /**
   * 设备删除事件
   * @param {Number} index - 设备索引
   */
  const handleDelGood = (index: number) => {
    const good = goodList.value.splice(index, 1)[0]
    if (good.id) {
      form.value.delMaterialIds.push(good.id)
    }
  }

  /**
   * 填充表单
   */
  const fillForm = () => {
    form.value.remark = detail.value.remark
    form.value.username = detail.value.receiptName
    form.value.phone = detail.value.receiptPhone
    form.value.province = detail.value.receiptProvince
    form.value.city = detail.value.receiptCity
    form.value.area = detail.value.receiptArea
    form.value.address = detail.value.receiptAddress
  }

  /**
   * 填充设备列表
   */
  const fillGoodList = async () => {
    for (let i = 0; i < materialList.value.length; i++) {
      const material = materialList.value[i]
      goodList.value.push({
        applyQty: String(material.applyQty),
        goodsCode: material.goodsCode,
        goodsId: material.goodsId,
        goodsName: material.goodsName,
        goodsSpec: material.goodsSpecName,
        goodsSpecId: material.goodsSpecId,
        grade: material.grade,
        id: material.id,
        inStore: '',
        inStoreId: material.inStoreId,
        inStorePosition: '',
        inStorePositionId: '',
        qty: String(material.qty),
        remark: material.remark,
        snCodes: material.stockCodeVos.map((item) => {
          return {
            snCode: item.code,
            snCodeId: '',
          }
        }),
        store: material.store,
        storeId: material.storeId,
        storePosition: '',
        storePositionId: '',
        type: material.type,
        unit: material.goodsUnit,
        classify: material.goodsType,
        storeStock: 0,
        inStoreStock: 0,
      })
    }

    allotInWarehouseIdForMultipleFillIn.value = goodList.value[0].inStoreId
    allotOutWarehouseIdForMultipleFillIn.value = goodList.value[0].storeId

    for (let i = 0; i < goodList.value.length; i++) {
      const good = goodList.value[i]
      getGoodStockParam.value = {
        goodsId: good.goodsId,
        goodsSpecId: good.goodsSpecId,
        storeId: good.storeId,
        storePositionId: '',
        type: good.type,
      }
      await getWarehouseGoodStock()
      goodList.value[i].storeStock = goodStock.value.systemStock

      getGoodStockParam.value = {
        goodsId: good.goodsId,
        goodsSpecId: good.goodsSpecId,
        storeId: good.inStoreId,
        storePositionId: '',
        type: good.type,
      }
      await getWarehouseGoodStock()
      goodList.value[i].inStoreStock = goodStock.value.systemStock

      const inWarehouse = allotInWarehouseOptions.value.find((item) => item.id === good.inStoreId)
      if (inWarehouse) {
        goodList.value[i].inStore = inWarehouse.name
      }
    }
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    resetForm()
    tagsViewStore.delView(route.path)
    router.push({ path: '/storage/allot/in', query: { isUpdate: 1 } })
  }

  onMounted(async () => {
    goodListInit()
    getReceiptCustomerList()

    form.value.typeId = fixedData.material_apply_id

    if (route.params.id) {
      await getDetail(route.params.id as string)
      fillForm()
      await getMaterialList(route.params.id as string)
      fillGoodList()
    }
    await getCurrentAccountsNetworkInWarehouseInfo()
    if (currentAccountsNetworkInWarehouseInfo.value) {
      allotInWarehouseIdForMultipleFillIn.value =
        currentAccountsNetworkInWarehouseInfo.value.inStroreId
      form.value.province = currentAccountsNetworkInWarehouseInfo.value.networkProvince
      form.value.city = currentAccountsNetworkInWarehouseInfo.value.networkCity
      form.value.area = currentAccountsNetworkInWarehouseInfo.value.networkArea
      form.value.address = currentAccountsNetworkInWarehouseInfo.value.networkAddress
      form.value.phone = userStore.$state.userInfo.phone
      form.value.username = userStore.$state.userInfo.name
      networkName.value = currentAccountsNetworkInWarehouseInfo.value.networkName
    }
    getAllotInWarehouseOptions(0)
    getAllotOutWarehouseOptions(0)
  })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
